import React, {Component, Fragment} from 'react';
import {inject, observer} from 'mobx-react';
import {toJS} from "mobx";
import {
    WeaLocaleProvider,
    WeaTab,
    WeaTop,
    WeaDialog,
    WeaNewScroll,
    WeaMoreButton,
    WeaRightMenu,
    WeaLeftRightLayout,
    WeaLeftTree,
    WeaOrgTree,
    WeaFormItem,
    WeaSearchGroup,
    WeaUpload,
    WeaCheckbox,
} from "ecCom";
import {WeaTableNew, WeaSwitch} from "comsMobx";
import {Button} from "antd";
import NoRightComponent from '../NoRightComponent';
import ImportMouldComponent from './ImportMouldComponent';
import EditPermissionComponent from './EditPermissionComponent';
import CommonConfig from '../../constant/CommonConfig';
import * as IconConstant from '../../constant/IconConstant';
import LanguageConstant from '../../constant/LanguageConstant';
import {timestamp} from '../../util/CommonUtil';
import '../../style/mouldListPage.less';

const {getLabel} = WeaLocaleProvider;
const {WeaTable} = WeaTableNew;

@inject("mouldStore", "importMouldStore", "editPermissionStore")
@observer
class MouldListPage extends Component {

    componentDidMount() {
        const {mouldStore} = this.props;
        mouldStore.getSystemSetting();
        mouldStore.getTableData();
        mouldStore.getMouldTypeTree();
    }


    render() {
        const {mouldStore, importMouldStore} = this.props;
        const {
            tableStore, authorized, loading, editMouldForm, selectedRowKeys, rowSelection, onOperatesClick, dialogVisible, saveForm,
            editMould, closeDialog, saveCallback, mouldType, getTableData, addMould, editPermission, editPermissionMouldId,
            detachedMaintenance, selectedSubCompanyId
        } = mouldStore;
        const {loading: importMouldLoading} = importMouldStore;
        const {saveMouldFiles, resetImportMouldComponent} = importMouldStore;
        if (!authorized) {
            return (<NoRightComponent/>);
        }
        const dialogTitle = this.getDialogTitle();
        const dialogStyle = this.getDialogStype();
        const dialogBtn = this.getDialogButtons();
        const renderTimeStamp = timestamp();
        return (
            <div className="mould-list-page">
                <WeaTop
                    title={getLabel("518592", "合同模板")}
                    icon={<i className={IconConstant.WEATOP_ICON}/>}
                    iconBgcolor={IconConstant.WEATOP_ICON_BG_COLOR}
                    buttons={this.getWeaTop()}
                    loading={loading}
                    showDropIcon={true}
                    dropMenuDatas={this.getDropMenuDatas()}
                >
                    <WeaLeftRightLayout
                        col={detachedMaintenance ? 3 : 2}
                        leftCom={detachedMaintenance ? this.getOrgTree() : this.getMouldTypeTree()}
                        midCom={this.getMouldTypeTree()}
                    >
                        <Fragment>
                            <WeaRightMenu datas={this.getDropMenuDatas()}>
                                <WeaTab
                                    searchType={['base']}
                                    onSearch={value => getTableData({name: value})}
                                />
                                <WeaTable
                                    hasOrder={true}
                                    needScroll={true}
                                    comsWeaTableStore={tableStore}
                                    getColumns={(cols) => this.getColumns(cols)}
                                    rowSelection={{
                                        selectedRowKeys: selectedRowKeys,
                                        onChange: rowSelection,
                                    }}
                                    onOperatesClick={onOperatesClick}
                                />
                            </WeaRightMenu>
                        </Fragment>
                    </WeaLeftRightLayout>
                </WeaTop>
                <WeaDialog
                    onCancel={closeDialog}
                    title={dialogTitle}
                    visible={dialogVisible}
                    style={dialogStyle}
                    hasScroll
                    buttons={dialogBtn}
                    icon={IconConstant.WEADIALOG_ICON}
                    iconBgcolor={IconConstant.WEADIALOG_ICON_BG_COLOR}
                    className="mould-list-page-dialog"
                >
                    {editMould ? (<div className="mould-list-page-dialog-editform">{this.renderEditForm()}</div>) : ""}
                    {addMould ? <ImportMouldComponent key={renderTimeStamp} defaultType={mouldType}
                                                      selectedSubCompanyId={selectedSubCompanyId}/> : ""}
                    {editPermission ? <EditPermissionComponent mouldId={toJS(editPermissionMouldId)}/> : ""}
                </WeaDialog>
            </div>
        )
    }


    /**
     * 弹框标题
     *
     * @returns {*}
     */
    getDialogTitle = () => {
        const {mouldStore} = this.props;
        const {editMould, addMould, editPermission} = mouldStore;
        if (editMould) {
            return getLabel(LanguageConstant.EDIT_MOULD, "编辑模板");
        } else if (addMould) {
            return getLabel(LanguageConstant.ADD_MOULD, "新建模板");
        } else if (editPermission) {
            return getLabel(LanguageConstant.MANAGE_PERMISSION, "管理权限");
        }
        return "";
    }

    /**
     * 弹框样式
     *
     * @returns {{width: number, height: number}}
     */
    getDialogStype = () => {
        const {mouldStore} = this.props;
        const {editMould, addMould, editPermission} = mouldStore;
        return editMould ? {width: '60%', height: 400} : {width: '60%', height: 680};
    }

    /**
     * 弹框操作按钮
     *
     * @returns {Array}
     */
    getDialogButtons = () => {
        const {mouldStore, importMouldStore, editPermissionStore} = this.props;
        const {editMould, addMould, editPermission, saveEditForm, loading} = mouldStore;
        const {loading: importMouldLoading, saveMouldFiles} = importMouldStore;
        const {loading: mouldPermissionLoading} = editPermissionStore;
        const dialogBtns = [];
        if (addMould) {
            dialogBtns.push(<Button type="primary" disabled={importMouldLoading}
                                    onClick={() => this.saveImportMould()}>{getLabel("30986", "保存")}</Button>)
        } else if (editMould) {
            dialogBtns.push(<Button type="primary" disabled={loading}
                                    onClick={() => saveEditForm()}>{getLabel("30986", "保存")}</Button>)
        } else if (editPermission) {
            dialogBtns.push(<Button type="primary" disabled={mouldPermissionLoading}
                                    onClick={() => this.saveMouldPermissions()}>{getLabel("30986", "保存")}</Button>)
        }
        return dialogBtns;
    }

    /**
     * 保存模板权限数据
     */
    saveMouldPermissions = () => {
        const {mouldStore, editPermissionStore} = this.props;
        const {closeDialog} = mouldStore;
        const {saveMouldPermissions, loading: mouldPermissionLoading} = editPermissionStore;
        saveMouldPermissions({}, () => {
            closeDialog();
        });
    }

    /**
     * 保存新建模板数据
     */
    saveImportMould = () => {
        const {mouldStore, importMouldStore} = this.props;
        const {closeDialog, getTableData} = mouldStore;
        const {loading: importMouldLoading, saveMouldFiles} = importMouldStore;
        saveMouldFiles(() => {
            closeDialog();
            getTableData();
        });
    }

    renderEditForm = () => {
        const {mouldStore} = this.props;
        const {editFormConditions, editMouldForm, uploadMouldChange} = mouldStore;
        const {isFormInit} = editMouldForm;
        let group = [];
        let col = 1;
        isFormInit && toJS(editFormConditions).map(c => {
            let items = [];
            c.items.map(field => {
                if (field.conditionType === 'UPLOAD' && field.domkey && field.domkey.includes("replacementFileId")) {
                    const {otherParams} = field;
                    const {maxMouldFileUploadSize, tip} = otherParams;
                    items.push({
                        com: (
                            <WeaFormItem
                                label={`${field.label}`}
                                labelCol={{span: `${6}`}}
                                ratio1to2
                                wrapperCol={{span: `${18}`}}>
                                <WeaUpload
                                    uploadUrl="/api/doc/upload/uploadFile"
                                    category="string"
                                    maxUploadSize={maxMouldFileUploadSize ? maxMouldFileUploadSize : CommonConfig.maxMouldFileUploadSize}
                                    limitType={CommonConfig.limitUploadMouldFileTypes}
                                    maxFilesNumber={1}
                                    viewAttr={2}
                                    isDetail={false}
                                    autoUpload={true}
                                    replaceWhenOver={false}
                                    showClearAll={false}
                                    onChange={(ids, list) => uploadMouldChange(ids, list)}
                                    datas={field.datas}
                                />
                                <div><span>{tip}</span></div>
                            </WeaFormItem>),
                        col: col,
                    });
                } else {
                    items.push({
                        com: (<WeaFormItem
                            label={`${field.label}`}
                            labelCol={{span: `${6}`}}
                            ratio1to2
                            tipPosition="bottom"
                            wrapperCol={{span: `${18}`}}>
                            <WeaSwitch fieldConfig={field} form={editMouldForm}/>
                        </WeaFormItem>),
                        col: col,
                    });
                }
            });
            group.push(<WeaSearchGroup needTigger={true} title={c.title} showGroup={true} items={items}/>)
        });
        return group;
    }

    getMouldTypeTree = () => {
        const {mouldStore} = this.props;
        const {mouldTypeTreeDatas, mouldTypeTreeRerender, mouldTypeTreeExpandedKeys, onMouldTypeTreeExpand, onMouldTypeTreeSelect} = mouldStore;
        return (
            <WeaLeftTree
                datas={toJS(mouldTypeTreeDatas)}
                defaultExpandLevel={1}
                onSelect={(key, topTabCount, countsType) => onMouldTypeTreeSelect(key, topTabCount, countsType)}
                key={mouldTypeTreeRerender}
                expandedKeys={toJS(mouldTypeTreeExpandedKeys)}
                onExpand={(keys, node) => onMouldTypeTreeExpand(keys, node)}
            />
        );
    }

    getOrgTree = () => {
        const {mouldStore} = this.props;
        const {onSelectBySubcompany} = mouldStore;
        return (
            <WeaOrgTree
                ref={'orgTree'}
                params={{rightStr: 'WorkflowManage:All'}}
                needSearch={true}
                inputLeftDom={`<b>${getLabel(25332, '组织结构')}</b>`}
                treeNodeClick={(event, ids, nodeids, nodes) => {
                    let subCompanyId = ids[0];
                    onSelectBySubcompany({subCompanyId});
                }}
            />
        );
    }

    getDropMenuDatas() {
        const {mouldStore, importMouldStore} = this.props;
        const {deleteBtnDisbled, openDialog, affirmDelete, managementAuth} = mouldStore;
        const {resetImportMouldComponent} = importMouldStore;
        if (!managementAuth) {
            return [];
        }
        const dropMenuDatas = [
            {
                key: '1',
                disabled: false,
                icon: <i className='icon-coms-Add-to'/>,
                content: getLabel("365", "新建"),
                onClick: key => {
                    resetImportMouldComponent();
                    openDialog("addMould");
                },
            },
            {
                key: '2',
                disabled: deleteBtnDisbled,
                icon: <i className='icon-coms-Batch-delete'/>,
                content: getLabel("32136", "批量删除"),
                onClick: key => affirmDelete("", true),
            },
        ];
        return dropMenuDatas;
    }

    getWeaTop() {
        const {mouldStore, importMouldStore} = this.props;
        const {deleteBtnDisbled, openDialog, affirmDelete, managementAuth} = mouldStore;
        const {resetImportMouldComponent} = importMouldStore;
        if (!managementAuth) {
            return [];
        }
        const btns = [
            <Button type="primary" onClick={() => {
                resetImportMouldComponent();
                openDialog("addMould");
            }}>{getLabel(365, "新建")}</Button>,
            <Button type="primary" disabled={deleteBtnDisbled}
                    onClick={() => affirmDelete("", true)}>{getLabel(32136, "批量删除")}</Button>,
        ]
        return btns;
    }


    getColumns(columns) {
        const {mouldStore} = this.props;
        const {openEditDialog} = mouldStore;
        return columns.map((col) => {
            if (col.dataIndex == 'f_name') {
                return {
                    ...col,
                    render: (text, record, index) => {
                        const {f_name, fileId} = record;
                        const link = `/contractmanagement/previewMould.jsp?imagefileId=${fileId}`;
                        return (
                            <a href={link} target="_blank">{f_name}</a>
                        )
                    },
                };
            }
            return col;
        });
    }

}

export default MouldListPage;